<template>
  <view class="material-series" v-if="list && list.length > 0">
    <view class="series-header">
      <text class="series-title">{{ title }}</text>
    </view>
    <view class="series-content" v-if="groupedList && Array.isArray(groupedList) && groupedList.length > 0">
      <block v-for="(group, groupIndex) in groupedList" :key="groupIndex">
        <!-- 分组标题 -->
        <view class="group-header" v-if="group && group.groupName && showCheckbox">
          <view class="group-title-wrapper">
            <text class="group-title">{{ getGroupNameText(group) }} </text>
            <dictLabel style="color: red;" :value="group.groupType" dict-type="btdm_package_group" />
            <!-- <text class="group-title"> 选 {{ getGroupSelectCount(group) }}</text> -->
          </view>
        </view>

        <!-- 分组内的产品列表 -->
        <view
          class="product-item"
          v-for="(item, index) in (group && Array.isArray(group.items) ? group.items : [])"
          :key="`${groupIndex}-${index}`"
          @click="onProductClick(item)"
        >
        <!-- 第一列：复选框 -->
        <view v-if="showCheckbox" class="product-checkbox" @click.stop="toggleSelect(item)">
          <view class="checkbox" :class="{ 'checked': item.selected, 'disabled': item.groupType !== '1' && item.selected }">
            <text class="checkmark" v-if="item.selected">✓</text>
          </view>
        </view>

        <!-- 第二列：产品图片 -->
        <view class="product-image-wrapper" :class="{ 'no-checkbox': !showCheckbox }">
          <image
            class="product-image"
            :src="getImageUrl(item)"
            mode="aspectFill"
            @error="onImageError"
          />
        </view>

        <!-- 第三列：产品详细信息 -->
        <view class="product-details">
          <!-- 第一行：产品名称和价格 -->
          <view class="detail-row">
            <view class="product-name">{{ item.basInv.cinvname || item.name }}</view>
            <view class="product-price">￥{{ item.iprice || '' }} {{  item.basInv && item.basInv.csacomunitname ? '/' + item.basInv.csacomunitname : '' }}</view>
          </view>

          <!-- 第二行：分组和数量 -->
          <view class="detail-row">
            <text class="detail-label">分组：{{ item.groupId || '' }}
            </text>
            <text class="detail-value">  {{  item.iqty ? 'x' + item.iqty : '' }}</text>
          </view>

          <!-- 第三行：类型和赠品 -->
          <view class="detail-row">
            
            <view class="detail-label">类型：
                 <dictLabel  style="margin-left: -10px;" :value="item.groupType" dict-type="btdm_package_group" />
            </view>
            <view class="gift-tag" v-if="item.bgift == '1'">
              <text class="gift-text">赠品</text>
            </view>
          </view>
        </view>
        </view>
      </block>
    </view>
  </view>
</template>

<script>
import dictLabel from "@/components/dictLabel.vue";
export default {
  components: {
    dictLabel,
  },
  name: 'MaterialSeries',
  props: {
    title: {
      type: String,
      default: '物料系列'
    },
    list: {
      type: Array,
      default: () => []
    },
    baseUrl: {
      type: String,
      default: ''
    },
    showCheckbox: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {

    }
  },
  data() {
    return {
      groupedList: []
    }
  },
  created() {
    console.log('MaterialSeries created, list:', this.list)
    // 在组件创建时就初始化数据
    this.$nextTick(() => {
      this.updateGroupedList()
    })
  },
  computed: {
  },
  mounted() {
    console.log('MaterialSeries mounted, list:', this.list)
    // 初始化数量
    this.initQuantity()
    // 初始化分组数据
    this.updateGroupedList()
    console.log('MaterialSeries groupedList:', this.groupedList)
  },
  watch: {
    list: {
      handler(newVal) {
        console.log('list changed:', newVal)
        this.$nextTick(() => {
          this.initQuantity()
          this.updateGroupedList()
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 更新分组数据
    updateGroupedList() {
      console.log('updateGroupedList called, list:', this.list)

      if (!this.list || this.list.length === 0) {
        console.log('list is empty, setting groupedList to []')
        this.groupedList = []
        return
      }

      try {
        // 按 groupId 分组
        const groups = {}
        this.list.forEach(item => {
          if (!item) return // 跳过空项

          const groupId = item.groupId || 'default'
          if (!groups[groupId]) {
            groups[groupId] = {
              groupId: groupId,
              // groupName: item.groupName || groupId, // 直接使用 groupName，避免复杂计算
              groupName: this.getGroupName(item),
              groupType: item.groupType,
              items: []
            }
          }
          groups[groupId].items.push(item)
        })

        // 转换为数组格式
        this.groupedList = Object.values(groups)
        console.log('updateGroupedList result:', this.groupedList)
      } catch (error) {
        console.error('更新分组数据失败:', error)
        this.groupedList = []
      }
    },
    initQuantity() {
      if (this.list && this.list.length > 0) {
        this.list.forEach(item => {
          if (!item.quantity) {
            this.$set(item, 'quantity', 1)
          }
          // selected 字段现在由父组件初始化，这里不再处理
          // if (item.selected === undefined) {
          //   // 如果 groupType 为 0，默认勾选且不允许取消
          //   console.log('初始化 groupType 为 0 的 item:', item.groupType, item.groupType == '0')
          //   this.$set(item, 'selected', item.groupType == '0')
          // }
        })
      }
    },
    toggleSelect(item) {
      // 如果 groupType 为 0，不允许取消勾选
      if (item.groupType !== '1' && item.selected) {
        return
      }
      item.selected = !item.selected
      this.$emit('item-select', { item, selected: item.selected })
    },
    getImageUrl(item) {
      if (item.basInv && item.basInv.picUrl) {
        // 如果是完整的URL，直接返回
        if (item.basInv.picUrl.startsWith('http')) {
          return item.basInv.picUrl
        }
        // 否则拼接baseUrl
        return this.baseUrl + item.basInv.picUrl
      }
      // 默认图片
      return '/static/image/commodity.png'
    },
    onImageError() {
      console.log('图片加载失败')
    },
    onProductClick(item) {
      this.$emit('product-click', item)
    },
    onQuantityChange(item, event) {
      item.quantity = event.value
      this.$emit('quantity-change', { item, quantity: event.value })
    },
    // 生成分组名称
    getGroupName(item) {
      if (!item.groupId) {
        return ''
      }

      // 获取同组的所有商品
      const groupItems = this.list.filter(listItem => listItem.groupId === item.groupId)
      // const groupCount = groupItems.length
      // list 的 groupQty 的总和
      const groupCount =  groupItems.reduce((total, listItem) => total + (listItem.groupQty || 0), 0)

      // 获取分组的选择数量限制
      let selectCount = item.groupQty || '1' // 默认选1
      // 获取分组名称
      let groupName = ''

      // 优先使用专门的分组名称字段
      if (item.groupName) {
        groupName = item.groupName
      } else if (item.groupTitle) {
        groupName = item.groupTitle
      } else {
        // 尝试从商品名称中智能提取分组名称
        groupName = `分组${item.groupId}`
      }

      return `${groupName} ${groupCount} 选 ${selectCount}`
    },

    // 获取分组名称文本部分（不包含数量）
    getGroupNameText(group) {
      if (!group || !group.items || group.items.length === 0) {
        return ''
      }

      const firstItem = group.items[0]
      let groupName = ''
      let groupId = ''

      // 优先使用专门的分组名称字段
      if (firstItem.groupName) {
        groupName = firstItem.groupName
        groupId = firstItem.groupId
      } else if (firstItem.groupTitle) {
        groupName = firstItem.groupTitle
        groupId = firstItem.groupId
      } else {
        // 尝试从商品名称中智能提取分组名称
        groupName = `分组${firstItem.groupId} `
        groupId = firstItem.groupId
      }
      return `${groupName} (${groupId})`
    },

    // 获取分组选择数量
    getGroupSelectCount(group) {
      if (!group || !group.items || group.items.length === 0) {
        return '1'
      }

      const firstItem = group.items[0]
      return firstItem.groupQty || '1'
    },
  }
}
</script>

<style lang="scss" scoped>
.material-series {
  // margin-bottom: 20rpx;
  background-color: #fff;
  
  .series-header {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .series-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .series-content {
    padding: 0 30rpx;

    // 分组标题样式
    .group-header {
      padding: 25rpx 0 15rpx 0;
      margin-top: 25rpx;
      border-bottom: 1rpx solid #f0f0f0;

      &:first-child {
        margin-top: 0;
      }

      .group-title-wrapper {
        display: flex;
        align-items: center;
        // justify-content: space-between;

        .group-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          position: relative;
          // flex: 1;

          &::before:nth-child(1){
            content: '•';
            color: #ff6b35;
            font-weight: bold;
            margin-right: 10rpx;
            font-size: 36rpx;
          }
        }
      }
    }
    
    .product-item {
      display: flex;
      /* align-items: flex-start; */
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      // 第一列：复选框
      .product-checkbox {
        width: 40rpx;
        margin-right: 20rpx;
        padding-top: 10rpx;

        .checkbox {
          width: 40rpx;
          height: 40rpx;
          border: 2rpx solid #ddd;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #fff;

          &.checked {
            background-color: #ff6b35;
            border-color: #ff6b35;

            .checkmark {
              color: #fff;
              font-size: 24rpx;
              font-weight: bold;
            }
          }

          &.disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }
        }
      }

      // 第二列：产品图片
      .product-image-wrapper {
        margin-right: 20rpx;

        &.no-checkbox {
          margin-left: 0;
        }

        .product-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          background-color: #f5f5f5;
        }
      }

      // 第三列：产品详细信息
      .product-details {
        flex: 1;

        .detail-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .product-name {
            flex: 1;
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
            line-height: 1.4;
            margin-right: 20rpx;
          }

          .product-price {
            font-size: 32rpx;
            color: #ff4757;
            font-weight: bold;
            white-space: nowrap;
          }

          .detail-label {
            font-size: 24rpx;
            color: #666;
            flex: 1;
          }

          .detail-value {
            font-size: 24rpx;
            color: #333;
          }

          .gift-tag {
            .gift-text {
              background-color: #ff6b35;
              color: #fff;
              font-size: 20rpx;
              padding: 4rpx 12rpx;
              border-radius: 20rpx;
            }
          }
        }
      }
    }
  }
}
</style>
